package admin;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import util.DBUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

@WebServlet("/adminLoginServlet")  //处理管理员注册和登录的功能，再加上邮件发送的功能
public class adminLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();

        try {
            String action = request.getParameter("action");
            if ("login".equals(action)) {
                String username = request.getParameter("username");
                String password = request.getParameter("password");

                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement stmt = conn.prepareStatement(
                             "SELECT * FROM admin WHERE username = ? AND password = ?")) {

                    stmt.setString(1, username);
                    stmt.setString(2, password);
                    ResultSet rs = stmt.executeQuery();

                    if (rs.next()) {
                        // 创建管理员session并设置相关属性
                        HttpSession session = request.getSession();
                        session.setAttribute("adminUsername", username);
                        session.setAttribute("adminAvatarUrl", rs.getString("avatarUrl"));
                        session.setAttribute("userType", "admin");
                        session.setAttribute("adminId", rs.getInt("id"));

                        // 检查是否存在用户session，如果存在则清除
                        if (session.getAttribute("username") != null) {
                            session.removeAttribute("username");
                            session.removeAttribute("userId");
                            session.removeAttribute("userAvatarUrl");
                        }

                        // 取出原来请求的页面
                        String redirectURL = (String) session.getAttribute("redirectAfterLogin");

                        if (redirectURL != null) {
                            response.sendRedirect(redirectURL);  // 回到原来的页面
                            session.removeAttribute("redirectAfterLogin"); // 避免后续重复跳转
                            out.print(mapper.writeValueAsString(Map.of(
                                    "status", "success"
                            )));
                        } else {
                            out.print(mapper.writeValueAsString(Map.of(
                                    "status", "success",
                                    "redirectUrl", "./admin/adminInfo.jsp"
                            )));
                        }

                    } else {
                        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        out.print(mapper.writeValueAsString(Map.of(
                            "status", "error", 
                            "message", "用户名或密码错误"
                        )));
                    }
                }
            } else if ("register".equals(action)) {
                String username = request.getParameter("username");
                String password = request.getParameter("password");

                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement checkStmt = conn.prepareStatement("SELECT id FROM admin WHERE username = ?");
                     PreparedStatement insertStmt = conn.prepareStatement(
                             "INSERT INTO admin(username, password) VALUES(?, ?)")) {

                    // 检查用户名是否存在
                    checkStmt.setString(1, username);
                    if (checkStmt.executeQuery().next()) {
                        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                        out.print(mapper.writeValueAsString(Map.of(
                            "status", "error", 
                            "message", "用户名已存在"
                        )));
                        return;
                    }

                    // 插入新管理员
                    insertStmt.setString(1, username);
                    insertStmt.setString(2, password);
                    int affectedRows = insertStmt.executeUpdate();

                    if (affectedRows > 0) {
                        out.print(mapper.writeValueAsString(Map.of("status", "success")));
                    } else {
                        throw new SQLException("创建管理员失败");
                    }
                }
            } else if ("logout".equals(action)) {
                HttpSession session = request.getSession(false);
                if (session != null) {
                    session.invalidate();
                }
                out.print(mapper.writeValueAsString(Map.of("status", "success")));
            }
        } catch (SQLException | JsonProcessingException e) {
            e.printStackTrace(); // 添加错误日志
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.print(mapper.writeValueAsString(Map.of(
                "status", "error", 
                "message", "服务器错误：" + e.getMessage()
            )));
        }
    }
}